var $sql = require('./userMapping');
var mysql = require('../../config/mysql');// 获取数据库连接配置

var config = require('../../config/config');//
var mapping = require('../mapping');//

var async = require('async');

var dateFormat = require('../../util/dateFormat');//


// 向前台返回JSON方法的简单封装
var jsonWrite = function (res, ret) {
    if(typeof ret === 'undefined') {
        res.json({
            code:'1',
            msg: '操作失败'
        });
    } else {
        res.json(ret);
    }
};



module.exports = {
    login: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = null;
        if(req.query.userName!=undefined){
            body=req.query;
            console.log('query');
        }else{
            body=req.body;
            console.log('body');
        }
        var userName=body.userName.trim(),passWord=body.passWord.trim();


        mysql.db.getConnection(function(connection){
            connection.beginTransaction(function(err) {
                if (err) {
                    console.log(err);
                    return;
                }
                var task1 = function(callback){
                    connection.query($sql.findName, [userName], function(err, result) {
                        if (err) {
                            console.log(err);
                            callback(err,null);
                            return;
                        }
                        console.log('第一次查询!');
                        if(result.length==0){
                            callback('用户名不存在',null);
                            return;
                        }
                        callback(null,result);
                    })
                }
                var task2 = function(callback){
                    connection.query($sql.findNameAndPass, [userName, passWord], function(err, result) {
                        if (err) {
                            console.log(err);
                            callback(err,null);
                            return;
                        }
                        console.log('第二次查询!');
                        if(result.length==0){
                            callback('用户名或密码不正确',null);
                            return;
                        }
                        connection.query($sql.logTime, [dateFormat.format('yyyy-MM-dd hh:mm:ss'), result[0].id], function(err, result) {
                            if (err) {
                                console.log(err);
                                callback(err,null);
                                return;
                            }
                            if(result.length==0){
                                callback('添加登录数据失败',null);
                                return;
                            }
                            callback(null,result);
                        })
                    })
                }
                async.series([task1, task2],function(err,result){
                    if (err) {
                        console.log(err);
                        //回滚
                        connection.rollback(function() {
                            console.log('出现错误,回滚!');
                            //释放资源
                            connection.release();
                            res.json({code:config.code.error,message:err,content:''})
                        });
                        return;
                    }
                    //提交
                    connection.commit(function(err) {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        console.log('成功,提交!');
                        //释放资源
                        connection.release();
                        var user={
                            userName:userName,
                            passWord:passWord
                        }
                        req.session.user=user;
                        res.json({code:config.code.success,message:config.message.success,content:result[0]})
                        //res.redirect('/index');
                    });
                })
            });
        })

        /*mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.findName, [userName], function(err, result) {
                if(result.length > 0) {
                    connection.query($sql.findNameAndPass, [userName, passWord], function(err, result) {
                        if(result.length > 0) {
                            var id=result[0].id;
                            connection.query($sql.logTime, [dateFormat.format('yyyy-MM-dd hh:mm:ss'), id], function(err, result) {
                                if(result.affectedRows > 0) {
                                    var user={
                                        userName:userName,
                                        passWord:passWord
                                    }
                                    req.session.user=user;
                                    console.log('登录成功'+userName);
                                    res.redirect('/index');
                                } else {
                                    result = {
                                        code: 2000,
                                        msg:'用户名或密码错误'
                                    };
                                    jsonWrite(res, result);
                                }

                            });
                        }else{
                            result = {
                                code: 2000,
                                msg:'用户名或密码错误'
                            };
                            jsonWrite(res, result);

                        }
                    });
                }else{
                    result = {
                        code: 2000,
                        msg:'用户名不存在'
                    };
                    jsonWrite(res, result);

                }
                connection.release();
            });
        });*/

    },
    add: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = null;
        if(req.query.userName!=undefined){
            body=req.query;
            console.log('query');
        }else{
            body=req.body;
            console.log('body');
        }

        var userName=body.userName || null,
            passWord=body.passWord || null,
            nickName=body.nickName || null,
            userPhoto=body.userPhoto || null,
            sex=body.sex || null

        if(userName == null || passWord == null){
            res.jsonp({ success: '200',  'message': '用户名或密码不能为空!'});
            return;
        }

        /* 设置字段名动态生成SQL和值 */
        var sqlObj=[
            {
                'name':'userName',
                'value':userName
            }, {
                'name':'passWord',
                'value':passWord
            }, {
                'name':'nickName',
                'value':nickName
            }, {
                'name':'userPhoto',
                'value':userPhoto
            }, {
                'name':'sex',
                'value':sex
            }
        ];
        var sqlObj=mapping.insert('t_user',sqlObj);  //根据表名 字段名动态生成SQL(sql)和写入数据库的值(sqlVal)
        /* 设置字段名动态生成SQL和值 END*/

        mysql.pool.getConnection(function(err, connection) {

            connection.query($sql.findName, [userName], function(err, result) {

                if(result.length > 0) {
                    result = {
                        code: 200,
                        msg:'该帐号已经注册'
                    };
                    jsonWrite(res, result);
                }else{
                    // 建立连接，向表中插入值
                    connection.query(sqlObj.sql, sqlObj.sqlVal, function(err, result) {
                        if(result.affectedRows > 0) {
                            //添加成功
                            res.redirect('list');
                        } else {
                            result = {
                                code: 200,
                                msg:'添加失败'
                            };
                            jsonWrite(res, result);
                        }

                    });
                }

                connection.release();

            });


        });
    },
    del: function (req, res, next) {
        // 获取前台页面传过来的参数
        console.log(req.query.id)
        if(req.query.id == null){
            jsonWrite(res, undefined);
            return;
        }
        // delete by Id
        mysql.pool.getConnection(function(err, connection) {
            var id = +req.query.id;
            connection.query($sql.del, [id], function(err, result) {
                if(result.affectedRows > 0) {
                    result = {
                        code: 200,
                        msg:'删除成功'
                    };
                } else {
                    result = void 0;
                }

                jsonWrite(res, result);

                connection.release();
            });
        });
    },
    editId: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = null;
        if(req.query.id!=undefined){
            body=req.query;
            console.log('query');
        }else{
            body=req.body;
            console.log('body');
        }
        var id=body.id || null;

        if(id == null) {
            res.jsonp({ success: '200',  'message': '用户id不能为空!'});
            return;
        }
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.findId, [id], function(err, result) {
                // 使用页面进行跳转提示
                if(result.length > 0) {
                    res.render('user/userAdd.html', { title: '添加用户', result:result});
                } else {
                    res.jsonp({ success: '200',  'message': '用户id不能为空!', 'result':result});
                }
                connection.release();
            });
        });

    },
    edit: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = null;
        if(req.query.id!=undefined){
            body=req.query;
            console.log('query');
        }else{
            body=req.body;
            console.log('body');
        }
        var id=body.id || null,
            userName=body.userName || null,
            passWord=body.passWord || null,
            nickName=body.nickName || null,
            userPhoto=body.userPhoto || null,
            sex=body.sex || null;

        if(id == null || userName == null || passWord == null) {
            res.jsonp({ success: '200',  'message': '用户id不能为空!'});
            return;
        }

        /* 设置字段名动态生成SQL和值 */
        var sqlObj=[
            {
                'name':'id',
                'value':id
            },
            {
                'name':'userName',
                'value':userName
            }, {
                'name':'passWord',
                'value':passWord
            }, {
                'name':'nickName',
                'value':nickName
            }, {
                'name':'userPhoto',
                'value':userPhoto
            }, {
                'name':'sex',
                'value':sex
            }, {
                'name':'upTime',
                'value':dateFormat.format('yyyy-MM-dd hh:mm:ss')
            }
        ];
        var sqlObj=mapping.update('t_user',sqlObj);  //根据表名 字段名动态生成SQL(sql)和写入数据库的值(sqlVal)
        /* 设置字段名动态生成SQL和值 END*/

        mysql.pool.getConnection(function(err, connection) {
            connection.query(sqlObj.sql, sqlObj.sqlVal, function(err, result) {
                // 使用页面进行跳转提示
                if(result.affectedRows > 0) {
                    res.redirect('list');
                } else {
                    result = {
                        code: 200,
                        msg:'修改失败'
                    };
                    jsonWrite(res, result);
                }

                connection.release();
            });
        });

    },
    findId: function (req, res, next) {
        // 获取前台页面传过来的参数
        if(req.query.id == null){
            res.jsonp({ success: '200',  'message': '查询id不能为空!'});
            return;
        }
        mysql.pool.getConnection(function(err, connection) {
            var id = req.query.id;
            connection.query($sql.findId, [id], function(err, result) {
                //jsonWrite(res, result);
                res.render('user/userList.html', { title: '所有用户用户信息', result:result, user:req.session.user});
                connection.release();

            });
        });
    },
    list: function (req, res, next) {
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.list, function(err, result) {
                connection.release();
                res.render('user/userList.html', { title: '所有用户用户信息', result:result, user:req.session.user});
            });
        });
    }

};